package com.qifan.alb2b.action.common;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * 验证码生成
 * 
 * @author lj
 * 
 */
@Controller
@RequestMapping("/vcode")

public class VcodeController {

	private static final int WIDTH = 70;
	private static final int HEIGHT = 21;

	private static final String[] EN_FONTS = "Arial,Arial Black,Tahoma,Times New Roman"
			.split(",");

	private static final String[] CH_FONTS = "宋体,微软雅黑,新宋体,黑体".split(",");

	private static final String[] EN_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz1234567890"
			.split("");

	private static final String[] CH_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz1234567890".split("");

	/** 日志记录 */
	private static Log logger = LogFactory.getLog(VcodeController.class);

	private static final List<Font> FONT = new ArrayList<Font>();

	static {
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();
		String[] fontNames = ge.getAvailableFontFamilyNames();
		for (String n : fontNames) {
			for (String o : EN_FONTS) {
				if (o.equals(n)) {
					FONT.add(new Font(n, Font.PLAIN, 16));
					FONT.add(new Font(n, Font.BOLD, 16));
					FONT.add(new Font(n, Font.ITALIC, 16));
				}
			}
			for (String o : CH_FONTS) {
				if (o.equals(n)) {
					FONT.add(new Font(n, Font.PLAIN, 16));
					FONT.add(new Font(n, Font.BOLD, 16));
					FONT.add(new Font(n, Font.ITALIC, 16));
				}
			}
		}
	}
	
	private String getChar(Random random,Font font){
		for (String o : EN_FONTS) {
			if(o.equals(font.getName())){
				return EN_CHARS[random.nextInt(EN_CHARS.length)];
			}
		}
		for (String o : CH_FONTS) {
			if(o.equals(font.getName())){
				return CH_CHARS[random.nextInt(CH_CHARS.length)];
			}
		}
		return "";
	}
	/**
	 * 获得验证码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getVcode.usr")
	public Object getVcode(HttpServletRequest request,HttpServletResponse response) {
		
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, WIDTH, HEIGHT);

		int x1 = 0;
		int y1 = random.nextInt(HEIGHT);
		int x2 = random.nextInt(WIDTH - x1);
		int y2 = random.nextInt(HEIGHT);

		Color c = new Color(random.nextInt(200), random.nextInt(200), random
				.nextInt(200));
		g.setColor(c);
		while (x1 < WIDTH) {
			((Graphics2D) g).setStroke(new BasicStroke(0.1f+random.nextFloat()));
			((Graphics2D) g).drawLine(x1, y1, x2, y2);
			x1 = x2;
			y1 = y2;
			x2 = x1 + random.nextInt(WIDTH);
			if (x2 <= x1) {
				x2 = x1 + 1;
			}
			y2 = random.nextInt(HEIGHT);
		}

		String sRand = "";
		for (int i = 0; i < 4; i++) {
			Font cf = FONT.get(random.nextInt(FONT.size()));
			String tmp = getChar(random,cf);
			sRand += tmp;
			g.setFont(cf);
			g.drawString(tmp, 15 * i + 5, 13 + random.nextInt(6));
		}
		g.dispose();

		sRand = sRand.toUpperCase();
		request.getSession().setAttribute("TAG_VCODE", sRand);
		try {
			ImageIO.write(image, "JPEG", response.getOutputStream());
		} catch (IOException e) {
			logger.error("验证码生成失败", e);
		}finally{			
			try {
				response.getOutputStream().flush();
				response.getOutputStream().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

}